/** 关于Sqlite数据库相关操作 */
export default class Sqlite {
	/** 构造方法 */
	constructor(databaseName, databasePath) {
		// 判断是否存在plus
		if(!plus) {
			throw new Error("不存在plus");
		}
		this.databaseName = databaseName;
		this.databasePath = databasePath;
		// 调用初始化方法...
		this.initDatabase();
	}
	
	
	/** 初始化数据库 */
	initDatabase() {
		// 判断数据库是否已经打开
		if(plus.sqlite.isOpenDatabase({ name: this.databaseName, path: this.databasePath })) {
			return;
		}
		// 打开数据库...
		this.open();
	}
	
	/** 处理打开数据库 */
	open() {
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				name: this.databaseName,
				path: this.databasePath,
				success: () => {
					resolve();
				},
				fail: error => {
					reject();
				}
			});
		});
	}
	
	/** 处理关闭数据库 */
	close() {
		return new Promise((resolve, reject) => {
			plus.sqlite.closeDatabase({
				name: this.databaseName,
				success: () => {
					resolve();
				},
				fail: () => {
					reject();
				}
			});
		});
	}

	/**
	 * 处理执行查询的SQL语句
	 * @param {string} sql
	 */
	select(sql) {
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: this.databaseName,
				sql,
				success: res => {
					resolve(res);
				},
				fail: error => {
					console.error('[sqlite][selectSql][error]', error)
					reject(error);
				}
			});
		});
	}
	
	/**
	 * 处理执行增删改的SQL语句
	 * @param {Array[string]|string} sql
	 */
	execute(sql) {
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: this.databaseName,
				sql,
				success: res => {
					resolve(res);
				},
				fail: error => {
					console.error('[sqlite][executeSql][error]', error)
					console.warn(sql);
					reject(error);
				}
			});
		});
	}

	/**
	 * 删除当前数据库下的某章表
	 * @param {string} tableName 表名
	 */
	deleteTable(tableName) {
		return this.execute(`drop table ${tableName};`);
	}
	
	/** 获取当前库下的所有表 - 目前用于测试 */
	getDataBaseTables() {
		return this.select(`select name from sqlite_master where type = 'table' order by name;`);
	}
	
	/** 生成唯一标识 */
	async createId() {
		let ids = await this.select(`select id from gen;`)
		if(ids.length<1) {
			await this.execute(`insert into gen (id) values (1);`)
			ids = await this.select(`select id from gen;`)
		}
		let maxId = ids[0].id
		maxId+=1
		await this.execute(`update gen set id=${maxId};`)
		return maxId
	}
	
	/**
	 * 清理某一张表的所有数据
	 * @param {string} tabelName 表名称 
	 */
	clearTable(tableName) {
		return this.execute(`delete from ${tableName}`);
	}
}